using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml.Serialization;

namespace SMSManager.Data
{
	internal class XmlTypeConverter<T> : TypeConverter
	{
		private const string WhiteSpacesPattern = @"(^[\t\r\n\s]*(?=<))|((?<=>)[\t\r\n\s]*(?=<))|((?<=>)[\t\r\n\s]*$)";

		public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type type)
		{
			return (type == typeof (string));
		}

		public override bool CanConvertTo(ITypeDescriptorContext ctx, Type type)
		{
			return (type == typeof (string));
		}

		public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data)
		{
			string value = data.ToString() == "." ? "" : data.ToString();

			value = Regex.Replace(value, WhiteSpacesPattern, "");

			var xmlSerializer = new XmlSerializer(typeof (T));
			using (var stringReader = new StringReader(value))
			{
				object result = xmlSerializer.Deserialize(stringReader);
				return result;
			}
		}

		public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)
		{
			if (!(value is T))
			{
				return new InvalidCastException();
			}
			var xmlSerializer = new XmlSerializer(typeof (T));
			using (var stringWriter = new StringWriter())
			{
				xmlSerializer.Serialize(stringWriter, value);
				stringWriter.Flush();
				string result = stringWriter.ToString();
				result = Regex.Replace(result, WhiteSpacesPattern, "");
				return result;
			}
		}
	}
}